<template>
  <el-cascader
    ref="elcascader"
    v-model="modelVal"
    :options="options"
    v-bind="elCascaderProps"
  ></el-cascader>
</template>
<script>
export default {
  name: 'CategorySelect',
  inject: {
    elForm: {
      default: {}
    }
  },
  props: {
    // v-model绑定的值
    value: {
      type: [String, Array],
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择分类'
    },
    label: {
      type: String,
      default: ''
    },
    // 可选最大等级，可以用来区分新增修改和选择产品分类
    // 给产品绑定分类时可以传入4，新增修改时选择父品类时需要小于4
    maxLevel: {
      type: Number,
      default: 2
    }
  },
  computed: {
    tagDisabled () {
      return this.elForm.disabled || this.disabled
    },
    elCascaderProps () {
      return {
        clearable: true,
        filterable: false,
        collapseTags: true,
        showAllLevels: false,
        placeholder: this.placeholder,
        ...this.$attrs,
        props: {
          emitPath: false,
          label: 'categoryName',
          value: 'id',
          ...this.$attrs.props
        }
      }
    }
  },
  watch: {
    value: {
      handler (n, o) {
        this.modelVal = n
      },
      immediate: true
    },
    modelVal (n) {
      this.$emit('change', n)
      this.$emit('input', n)
      let node = this.$refs.elcascader.getCheckedNodes()
      if (node.length > 0) {
        this.$emit('label:update', node[0]?.label)
      }
      this.$parent.$nextTick(() => {
        this.$parent.$emit('el.form.blur', n) // 触发父组件表单校验
      })
    }
  },
  data () {
    return {
      options: [],
      modelVal: ''
    }
  },
  created () {
    this.getData()
  },
  methods: {
    getData () {
      this.$POST('sot-admin-api/product/category/queryCategoryTree', {
        level: this.maxLevel
      }).then(res => {
        if (res.errorCode === '00000') {
          this.options = res.data.children || []
        }
      })
    }
  }
}
</script>
